import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_image_gallery_saver/flutter_image_gallery_saver.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import 'package:intl/intl.dart';
import '../common/extension/string_extension.dart';

import '../common/constants.dart';
import '../common/emoji_util.dart';
import '../common/routes.dart';
import '../common/utils.dart';
import '../controllers/pipe_comment_controller.dart';
import '../model/pipe_comment_data.dart';
import '../widgets/attributed_label.dart';

class PipeCommentPage extends StatelessWidget {
  PipeCommentPage({super.key});

  final PipeCommentController controller = Get.find<PipeCommentController>();

  /// 格式化时间
  /// [dateString] 输入的日期字符串（格式如 "yyyy-MM-dd HH:mm:ss"）
  /// 返回动态显示的时间文本：刚刚、几分钟前、几小时前、MM-dd
  String _formatTime(String dateString) {
    try {
      // 将输入的日期字符串解析为 DateTime 对象
      DateTime inputTime = DateTime.parse(dateString);
      DateTime now = DateTime.now();

      // 计算时间差（单位：秒）
      Duration difference = now.difference(inputTime);
      int seconds = difference.inSeconds;

      if (seconds < 60) {
        return "刚刚"; // 小于1分钟
      } else if (seconds < 3600) {
        return "${difference.inMinutes}分钟前"; // 小于1小时
      } else if (seconds < 86400) {
        return "${difference.inHours}小时前"; // 小于24小时
      } else {
        return DateFormat("MM-dd").format(inputTime);
      }
    } catch (e) {
      return dateString;
    }
  }

  _buildReplyList(List<PipeCommentModel> replyList) {
    final items = replyList.map((comment) {
      final time = _formatTime(comment.createdTime);
      final replacements = EmojiUtil.emojiMap();
      return Container(
        margin: EdgeInsets.only(bottom: 12),
        width: double.infinity,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            CircleAvatar(
              radius: 10,
              backgroundImage: NetworkImage(comment.user.avatar ?? ''),
            ),
            SizedBox(
              width: 6,
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Flexible(
                        child: Text(
                          comment.user.nickname ?? '',
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: Colors.white54),
                        ),
                      ),
                      if (controller.uid == comment.user.uid)
                        Container(
                          margin: EdgeInsets.symmetric(horizontal: 3),
                          padding: EdgeInsets.symmetric(horizontal: 3),
                          decoration: BoxDecoration(color: Constants.themeColor, borderRadius: BorderRadius.circular(3)),
                          child: Text(
                            "作者",
                            style: TextStyle(fontSize: 11, color: Colors.white),
                          ),
                        ),
                      if (comment.replyUser != null)
                        Icon(
                          Icons.play_arrow,
                          color: Colors.white54,
                          size: 20,
                        ),
                      if (comment.replyUser != null)
                        Text(
                          comment.replyUser?.nickname ?? '',
                          style: TextStyle(color: Colors.white54),
                        ),
                    ],
                  ),
                  if (comment.content != null)
                    Padding(
                      padding: EdgeInsets.only(right: 30),
                      child: AttributedLabel(
                        text: comment.content ?? '',
                        replacements: replacements,
                        style: TextStyle(color: Colors.white, fontSize: 15),
                      ),
                    ),
                  if (comment.isAuthorLike == 1)
                    Container(
                      margin: EdgeInsets.symmetric(vertical: 3),
                      padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                      decoration: BoxDecoration(color: Color(0xFF1F3A22), borderRadius: BorderRadius.circular(3)),
                      child: Text(
                        "作者赞过",
                        style: TextStyle(fontSize: 11, color: Color(0xFF31D53C)),
                      ),
                    ),
                  if (comment.imgUrl != null)
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 6),
                      child: GestureDetector(
                        child: CachedNetworkImage(
                          imageUrl: (comment.imgUrl ?? '').getThumbUrl(size: 200),
                          fit: BoxFit.cover,
                          width: 100,
                          height: 100,
                          placeholder: (context, url) {
                            return Container(
                              color: Colors.white24,
                            );
                          },
                        ),
                        onTap: () {
                          _previewPhoto(comment.imgUrl ?? '');
                        },
                      ),
                    ),
                  Row(
                    children: [
                      Text(
                        "$time・${isEmpty(comment.province) ? '' : comment.province}",
                        style: TextStyle(color: Colors.white54),
                      ),
                      SizedBox(
                        width: 20,
                      ),
                      GestureDetector(
                        child: Text(
                          "回复",
                          style: TextStyle(color: Colors.white70, fontSize: 15),
                        ),
                        onTap: () {},
                      ),
                      Spacer(),
                      Text(
                        "${comment.likes > 0 ? comment.likes : ''}",
                        style: TextStyle(color: Colors.white70),
                      ),
                      GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        child: SizedBox(
                          width: 24,
                          height: 24,
                          child: Icon(comment.userSelfLikes == 1 ? Icons.favorite : Icons.favorite_outline, color: comment.userSelfLikes == 1 ? Colors.red : Colors.white70, size: 16),
                        ),
                        onTap: () {
                          if (comment.userSelfLikes == 1) {
                            controller.cancelLikeComment(comment.id, comment.pid);
                          } else {
                            controller.addLikeComment(comment.id, comment.pid);
                          }
                        },
                      ),
                    ],
                  ),
                ],
              ),
            )
          ],
        ),
      );
    }).toList();
    return Padding(
      padding: EdgeInsets.only(top: 10),
      child: Column(
        children: items,
      ),
    );
  }

  Widget _buildCommentListItem(BuildContext context, int index) {
    if (index == controller.commentList.length) {
      if (controller.hasMore.value) {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: CircularProgressIndicator(
              strokeWidth: 1,
              color: Constants.themeColor,
            ),
          ),
        );
      } else {
        return Center(
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Text(
              "没有更多数据了",
              style: TextStyle(color: Colors.white54),
            ),
          ),
        );
      }
    }

    final comment = controller.commentList[index];
    final time = _formatTime(comment.createdTime);
    final replyTotal = comment.total ?? 0;
    final replyList = comment.replyList ?? [];
    final replacements = EmojiUtil.emojiMap();
    return Container(
      margin: EdgeInsets.only(bottom: 15),
      width: double.infinity,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(
            radius: 20,
            backgroundImage: NetworkImage(comment.user.avatar ?? ''),
          ),
          SizedBox(
            width: 6,
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      comment.user.nickname ?? '',
                      style: TextStyle(color: Colors.white54),
                    ),
                    if (controller.uid == comment.user.uid)
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 3),
                        padding: EdgeInsets.symmetric(horizontal: 3),
                        decoration: BoxDecoration(color: Constants.themeColor, borderRadius: BorderRadius.circular(3)),
                        child: Text(
                          "作者",
                          style: TextStyle(fontSize: 11, color: Colors.white),
                        ),
                      ),
                  ],
                ),
                if (comment.content != null)
                  Padding(
                    padding: EdgeInsets.only(right: 30),
                    child: AttributedLabel(
                      text: comment.content ?? '',
                      replacements: replacements,
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  ),
                if (comment.isTop == 1)
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 3),
                    padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                    decoration: BoxDecoration(color: Color(0xFF1F3A22), borderRadius: BorderRadius.circular(3)),
                    child: Text(
                      "置顶",
                      style: TextStyle(fontSize: 11, color: Color(0xFF31D53C)),
                    ),
                  ),
                if (comment.isAuthorLike == 1)
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 3),
                    padding: EdgeInsets.symmetric(horizontal: 3, vertical: 1),
                    decoration: BoxDecoration(color: Color(0xFF1F3A22), borderRadius: BorderRadius.circular(3)),
                    child: Text(
                      "作者赞过",
                      style: TextStyle(fontSize: 11, color: Color(0xFF31D53C)),
                    ),
                  ),
                if (comment.imgUrl != null)
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 6),
                    child: GestureDetector(
                      child: CachedNetworkImage(
                        imageUrl: (comment.imgUrl ?? '').getThumbUrl(size: 200),
                        fit: BoxFit.cover,
                        width: 100,
                        height: 100,
                        placeholder: (context, url) {
                          return Container(
                            color: Colors.white24,
                          );
                        },
                      ),
                      onTap: () {
                        _previewPhoto(comment.imgUrl ?? '');
                      },
                    ),
                  ),
                Row(
                  children: [
                    Text(
                      "$time・${isEmpty(comment.province) ? '' : comment.province}",
                      style: TextStyle(color: Colors.white54),
                    ),
                    SizedBox(
                      width: 20,
                    ),
                    GestureDetector(
                      child: Text(
                        "回复",
                        style: TextStyle(color: Colors.white70, fontSize: 15),
                      ),
                      onTap: () {},
                    ),
                    Spacer(),
                    Text(
                      "${comment.likes > 0 ? comment.likes : ''}",
                      style: TextStyle(color: Colors.white70),
                    ),
                    GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      child: SizedBox(
                        width: 24,
                        height: 24,
                        child: Icon(comment.userSelfLikes == 1 ? Icons.favorite : Icons.favorite_outline, color: comment.userSelfLikes == 1 ? Colors.red : Colors.white70, size: 16),
                      ),
                      onTap: () {
                        if (comment.userSelfLikes == 1) {
                          controller.cancelLikeComment(comment.id, null);
                        } else {
                          controller.addLikeComment(comment.id, null);
                        }
                      },
                    ),
                  ],
                ),
                if (replyList.isNotEmpty) _buildReplyList(replyList),
                if (replyTotal > replyList.length)
                  GestureDetector(
                    child: Row(
                      children: [
                        Container(
                          color: Colors.white54,
                          width: 20,
                          height: 1,
                        ),
                        SizedBox(
                          width: 4,
                        ),
                        Text(
                          "展开 ${(replyTotal - replyList.length)} 条回复",
                          style: TextStyle(color: Colors.white54, fontSize: 13),
                        ),
                        Icon(
                          Icons.keyboard_arrow_down,
                          color: Colors.white54,
                        )
                      ],
                    ),
                    onTap: () {
                      int count = comment.replyList?.length ?? 0;
                      int pageNo = (count / 5).floor() + 1;
                      controller.getPipeCommentReplyList(comment.id, pageNo);
                    },
                  )
              ],
            ),
          )
        ],
      ),
    );
  }

  _buildCommentList() {
    if (controller.isLoading.value) {
      return Center(
        child: SizedBox(
          width: 30,
          height: 30,
          child: CircularProgressIndicator(
            strokeWidth: 1,
            color: Constants.themeColor,
          ),
        ),
      );
    } else {
      if (controller.commentList.isNotEmpty) {
        return ListView.builder(controller: controller.scrollController, padding: EdgeInsets.zero, itemCount: controller.commentList.length + 1, itemBuilder: _buildCommentListItem);
      }
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "暂无评论",
              style: TextStyle(
                color: Colors.grey,
                fontSize: 16,
              ),
            ),
            SizedBox(height: 16),
            OutlinedButton.icon(
              style: OutlinedButton.styleFrom(
                foregroundColor: Color(0xFF1AC432),
                side: BorderSide(color: Color(0xFF1AC432), width: 1),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
              ),
              onPressed: () {
                Get.toNamed(Routes.COMMENT_INPUT, arguments: {"showEmojiPanel": false});
              },
              icon: Icon(
                Icons.edit,
                color: Color(0xFF1AC432),
                size: 16,
              ),
              label: Text(
                "发布第一条评论",
                style: TextStyle(fontSize: 15),
              ),
            ),
          ],
        ),
      );
    }
  }

  _previewPhoto(String imageUrl) async {
    showDialog(
      context: Get.context!,
      useSafeArea: false,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.black,
          insetPadding: EdgeInsets.zero,
          child: Column(
            children: [
              SizedBox(
                height: Get.mediaQuery.padding.top,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  IconButton(
                    onPressed: () {
                      Get.back();
                    },
                    icon: Icon(
                      Icons.close,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              SizedBox(
                width: double.infinity,
                height: Get.height - 200,
                child: CachedNetworkImage(
                  imageUrl: imageUrl,
                ),
              ),
              GestureDetector(
                child: Container(
                  margin: EdgeInsets.only(top: 10),
                  width: 150,
                  height: 40,
                  decoration: BoxDecoration(
                    color: Constants.themeColor,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.download,
                        color: Colors.white,
                        size: 16,
                      ),
                      Text(
                        "保存到相册",
                        style: TextStyle(color: Colors.white),
                      )
                    ],
                  ),
                ),
                onTap: () async {
                  var response = await Dio().get(imageUrl, options: Options(responseType: ResponseType.bytes));
                  await FlutterImageGallerySaver.saveImage(Uint8List.fromList(response.data));
                  Fluttertoast.showToast(msg: "保存成功", gravity: ToastGravity.CENTER);
                },
              )
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black12,
      resizeToAvoidBottomInset: false,
      body: Obx(() {
        return Column(
          children: [
            GestureDetector(
                behavior: HitTestBehavior.opaque,
                child: Container(height: 100),
                onTap: () {
                  Get.back();
                }),
            Container(
              decoration: BoxDecoration(
                color: Color(0xFF171717),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(16),
                  topRight: Radius.circular(16),
                ),
              ),
              width: double.infinity,
              height: MediaQuery.of(context).size.height - 100,
              padding: EdgeInsets.only(left: 10, top: 15, right: 10, bottom: 5),
              child: Column(
                children: [
                  Row(
                    children: [
                      Padding(
                        padding: EdgeInsets.only(left: 5),
                        child: Text(
                          "评论",
                          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16),
                        ),
                      ),
                      Spacer(),
                      GestureDetector(
                        child: Icon(
                          Icons.close,
                          color: Colors.white38,
                        ),
                        onTap: () {
                          Get.back();
                        },
                      )
                    ],
                  ),
                  SizedBox(
                    height: 10,
                  ),
                  Expanded(
                    child: _buildCommentList(),
                  ),
                  GestureDetector(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 0),
                      margin: EdgeInsets.only(bottom: 12),
                      decoration: BoxDecoration(
                        color: Color(0xFF1F1F1F),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Row(
                        children: [
                          Text(
                            "发评论...",
                            style: TextStyle(color: Colors.white54),
                          ),
                          Spacer(),
                          InkWell(
                            child: Container(
                              padding: EdgeInsets.symmetric(horizontal: 5, vertical: 10),
                              child: Icon(
                                Icons.image,
                                color: Colors.white,
                                size: 20,
                              ),
                            ),
                            onTap: () {},
                          ),
                          InkWell(
                            child: Container(
                              padding: EdgeInsets.symmetric(horizontal: 5, vertical: 10),
                              child: Icon(
                                Icons.emoji_emotions,
                                color: Colors.white,
                                size: 20,
                              ),
                            ),
                            onTap: () {
                              Get.toNamed(Routes.COMMENT_INPUT, arguments: {"showEmojiPanel": true});
                            },
                          ),
                        ],
                      ),
                    ),
                    onTap: () {
                      Get.toNamed(Routes.COMMENT_INPUT, arguments: {"showEmojiPanel": false});
                    },
                  ),
                  SizedBox(
                    height: Get.mediaQuery.padding.bottom,
                  ),
                ],
              ),
            )
          ],
        );
      }),
    );
  }
}
